<?php

/**
 * @name IndexController
 * @author root
 * @desc 默认控制器
 * @see http://www.php.net/manual/en/class.yaf-controller-abstract.php
 */
class UserController extends Yaf_Controller_Abstract
{
    /**
     * 默认初始化方法，如果不需要，可以删除掉这个方法
     * 如果这个方法被定义，那么在Controller被构造以后，Yaf会调用这个方法
     */
    public function init()
    {
        $this->getView()->assign("header", "Yaf Example");
    }

    public function indexAction()
    {
        return $this->loginAction();
    }

    /**
     * 登录
     * @return false 登录成功或失败
     */
    public function loginAction()
    {
        $submit = Common_Request::getRequest("submit", "0");
        if ($submit != "1") {
            echo json_encode(Err_Map::get(1001));
            return FALSE;
        }
        //获取参数
        $uname = Common_Request::postRequest('uname', false);
        $pwd = Common_Request::postRequest('pwd', false);
        if (!$uname || !$pwd) {
            echo json_encode(Err_Map::get(1002));
            return FALSE;
        }
        try {
            //调用Model，做登录验证
            $model = new UserModel();
            $uid = $model->login(trim($uname), trim($pwd));
        } catch (Exception $e) {
            echo json_encode(Err_Map::get(1000));
            return FALSE;
        }
        if ($uid) {
            session_start();
            $_SESSION['user_token'] = md5("salt" . $_SERVER['REQUEST_TIME'] . $uid);
            $_SESSION['user_token_time'] = $_SERVER['REQUEST_TIME'];
            $_SESSION['user_id'] = $uid;
            echo Common_Request::response(0, "", array("name" => $uname));
        } else {
            echo Common_Request::response($model->errno, $model->errmsg);
        }
        return FALSE;
    }

    /**
     * 注册
     * @return false 注册成功或失败
     */
    public function registerAction()
    {
        //获取参数
        $uname = $this->getRequest()->getPost('uname', false);
        $pwd = $this->getRequest()->getPost('pwd', false);
        if (!$uname || !$pwd) {
            echo json_encode(Err_Map::get(1002));
            return FALSE;
        }
        //调用Model，做登录验证
        $model = new UserModel();
        if ($model->register(trim($uname), trim($pwd))) {
            echo Common_Request::response(0, "", ['name' => $uname]);
        } else {
            echo Common_Request::response($model->errno, $model->errmsg);
        }
        return false;
    }
}
